<?php
/**
 * @author by bilee.
 * 时间: 17/2/7 下午8:38
 * 管理APP接口
 */
namespace Api\Controller;

use Common\Controller\HomebaseController;

/**
 * Class AdminController
 * 管理员手机端
 * @package Api\Controller
 */
class AdminController extends HomebaseController
{

    /**
     * @api {get} managerLogin/mobile/:mobile/user_pass/:user_pass/ 管理用户登录
     * @apiGroup pt
     * @apiName 管理员登录
     *
     * @apiParam {Int} mobile 用户手机号.
     * @apiParam {String} user_pass 密码.
     **/
    function managerLogin()
    {
        $mobile = I("mobile");
        $user_pass = I("user_pass");
        if (!$mobile || !$user_pass) {
            return RET_NO_V(2, "手机号或密码未填写");
        }

        $manager_db = M("app_manager");
        $manager = $manager_db->where(array('mobile' => $mobile, 'user_pass' => md5($user_pass)))->find();

        if ($manager) {
            if (0 == $manager['user_status']) {
                return RET_NO_V(0, "您的账号已被停用，请联系客服！");
            }
            //===============更新账户信息=========================================
            $rets = $manager_db->where(array('mobile' => $mobile))->save(array('token' => md5(uniqid(rand())), 'last_login_time' => date('Y-m-d H:i:s', time())));
            if ($rets) {
                $manager_obj = $manager_db->where(array('id' => $manager['id']))->find();
                return RET(1, "登录成功", $manager_obj);
            } else {
                return RET_NO_V(0, "登录失败，请稍后再试");
            }
        } else {
            return RET_NO_V(0, "用户名或密码错误，请重试");
        }
    }

    /**
     * @api {get} convertOrder/uid/:uid/token/:token/ 获取可以转的订单
     * @apiGroup pt
     * @apiName 获取可以转的订单
     *
     * @apiParam {Int} uid 用户ID.
     * @apiParam {String} token 鉴权码.
     **/
    function convertOrder()
    {
       managerificationToken();
        $order_resmsm = M('order_resmsm');
        $order_resmsm_data = $order_resmsm->where(array('pay_status' => 1, 'status' => 2))->select();
//        dump($order_resmsm_data);
//        die;
        $ret_data = array();
        for ($i = 0; $i < count($order_resmsm_data); $i++) {
            $ret_data[] = json_decode($order_resmsm_data[$i]['order_data'], true);
            $ret_data[$i]['dispatch_name'] = get_dispatch_name($order_resmsm_data[$i]['dispatch_id']);
            $ret_data[$i]['mobile'] = get_dispatch_tel($order_resmsm_data[$i]['dispatch_id']);
            $ret_data[$i]['order_time'] = $order_resmsm_data[$i]['order_time'];
        }
//        dump($ret_data);
//        die;
        if ($ret_data) {
            return RET(1, "获取订单数据成功！", $ret_data);
        } else {
            return RET_NO_V(0, "暂无数据！");
        }
    }

    /**
     * @api {get} dispatchList/uid/:uid/token/:token 可以指派的跑男
     * @apiGroup pt
     * @apiName 可以指派的跑男
     *
     * @apiParam {Int} uid 用户ID.
     * @apiParam {String} token 鉴权码.
     **/
    function dispatchList()
    {
        managerificationToken();
        $dispatch = M('dispatch');
        $dispatch_data = $dispatch->where(array('work_status' => 1, 'is_audit' => 2, 'is_sign' => 2))->field('dispatch_name,avatar,dispatch_id,place_up_time,mobile')->select();
        if ($dispatch_data) {
            return RET(1, "获取可指派的跑客数据成功！", $dispatch_data);
        } else {
            return RET_NO_V(0, "暂无数据！");
        }
    }

    /**
     * @api {get} dispatchSerach/uid/:uid/token/:token/dispatch_name/:dispatch_name/ 跑客搜索
     * @apiGroup pt
     * @apiName 跑客搜索
     *
     * @apiParam {Int} uid 用户ID.
     * @apiParam {String} token 鉴权码.
     * @apiParam {String} dispatch_name 跑客姓名.
     **/
    function dispatchSerach()
    {
        managerificationToken();
        $dispatch = M('dispatch');
        $dispatch_name = I('dispatch_name');
        $dispatch_data = $dispatch->where(array('work_status' => 1, 'is_audit' => 2, 'is_sign' => 2,'dispatch_name'=>array('LIKE','%'.$dispatch_name.'%')))->field('dispatch_name,avatar,dispatch_id,place_up_time,mobile')->select();
        if ($dispatch_data) {
            return RET(1, "获取跑客数据成功！", $dispatch_data);
        } else {
            return RET_NO_V(0, "暂无数据！");
        }
    }


    /**
     * @api {get} orderDetail/uid/:uid/token/:token/order_id/:order_id/ 订单详情
     * @apiGroup pt
     * @apiName 订单详情
     *
     * @apiParam {Int} uid 用户ID.
     * @apiParam {String} token 鉴权码.
     * @apiParam {Int} order_id 订单ID.
     **/

    function orderDetail()
    {
        managerificationToken();
        $order_resmsm = M('order_resmsm');
        $order_resmsm_data = $order_resmsm->where(array('order_id'=>I('order_id')))->field('order_data')->find();
        if ($order_resmsm_data['order_data']) {
            return RET(1, "获取订单数据成功！", json_decode($order_resmsm_data['order_data'],true));
        } else {
            return RET_NO_V(0, "暂无数据！");
        }
    }





    /**
     * @api {get} convertDispatch/uid/:uid/token/:token/order_id/:order_id/dispatch_id/:dispatch_id 订单转出给某个人
     * @apiGroup pt
     * @apiName 单转出给某个人
     *
     * @apiParam {Int} dispatch_id 跑客ID.
     * @apiParam {Int} order_id 订单ID.
     **/
    function convertDispatch()
    {
        managerificationToken();
        $new_dispatch_id = I('dispatch_id');
        $order_id = I('order_id');

        $dispatch_db = M('dispatch');
        $new_dis_obj = $dispatch_db->where(array('dispatch_id' => $new_dispatch_id, 'is_sign' => 2, 'account_status' => 1))->find();
        if (!$new_dispatch_id) {
            return RET_NO_V(0, "新跑客信息有误！");
        }
        $order_db = M('order');
        $order_obj = $order_db->where('order_id=' . $order_id . '  and status > 1 and status < 7')->find();

        if (!$order_obj) {
            return RET_NO_V(0, "订单已完成或取消，不能转单！");
        }
        if ($new_dispatch_id == $order_obj['dispatch_id']) {
            return RET_NO_V(0, "跑客不能转单给自己");
        }

        //=======临时取消保险  2016-12-29 19:01:27
        //$old_dis_count = pnrob_count($order_obj['dispatch_id'],$order_obj['order_time']);

        //if($old_dis_count == 1){//今天第一单，退还保险费
        //    $insu_ret = dispatch_insurance_options($order_obj['dispatch_id'],$order_id,2,9,'退还保险费','您今天接的第一个订单（'.$order_obj['order_number'].'）已转给其他跑客，退还保险费2.00元','您今天接的第一个订单（'.$order_obj['order_number'].'）已转给其他跑客，退还保险费2.00元');
        //}
        //$new_dis_count =  pnrob_count($new_dispatch_id,$order_obj['order_time']);

        //if($new_dis_count == 0 ){//今天第一单，扣除保险费
        //    $insu_ret = dispatch_insurance_options($new_dispatch_id, $order_id, -2, 6, '扣除保险费', '每天首次接单扣除保险费2.00元', '这是一个转单，且是您今天首次接单（' . $order_obj['order_number'] . '）扣除保险费2.00元');
        //}
        $dispatch_get_money = get_pnOrderAccount($order_id, $new_dispatch_id);

        $ret = $order_db->where(array('order_id' => $order_id))->save(array(
            //更改单子的抢单状态
            'dispatch_id' => $new_dispatch_id,
            //更改单子抢单最后时间
            'dispatch_end_time' => date('Y-m-d H:i:s'),//更新此跑客接单的时间
            'dispatch_get_money' => $dispatch_get_money
        ));

        $order_resmsm_upret = M('order_resmsm')->where(array('order_id' => $order_id))
            ->setField(array('dispatch_id' => $new_dispatch_id));

        $order_trun = M('order_turn')->add(array('order_id' => $order_id, 'new_dispatch_id' => $new_dispatch_id, 'old_dispatch_id' => $order_obj['dispatch_id'], 'turn_time' => date('Y-m-d H:i:s', time()), 'remark' => '转单','trun_client'=>1,'operator_id'=>I('uid')));

        $msg_ret = create_dispatch_message($new_dispatch_id, '转单', '订单（' . $order_obj['order_number'] . '）已转单给您', '订单（' . $order_obj['order_number'] . '）已转单给您，请查看订单详情');

        if ($ret && $order_resmsm_upret && $order_trun && $msg_ret) {
            return RET_NO_V(1, "转单成功！");
        } else {
            return RET_NO_V(0, "转单失败，请提供单号给客服解决！");
        }
    }
     /**
     * @api{get} heavyBuyer/uid/:uid/token/:token/ 获取大客户数据
     * @apiName 获取大客户数据
     * @apiGroup pt
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *"retCode": 1,
     *"retDesc": "成功！",
     *"retValue": {
     *"shop_name": 永利水果,           //客户名称
     * "shop_address":圣菲城            //客户地址
     *"shop_latit": 34.8152060000, //客户地址纬度
     *"shop_longit": 113.6397350000, //客户地址经度
     *"shop_scope": 水果,      //主营范围
     *"shop_area": 北区, //客户区域主营范围
     *"order_counts" :10 //该商户当天的订单数
     *"order_amount" :81.00 //该商户当天的总消费金额
     *"real_amount"  :81.00 //该商户当天的实际消费金额
     *}
     *}
     **/
    function  heavyBuyer(){
       managerificationToken();
//        $user_shop = M("user_shop");
//        $ret_data = $user_shop->order('sort')->Field('shop_name,shop_address,shop_latit,shop_longit,shop_scope,shop_area')->select();
//        dump($ret_data);
//        die;
    //********************************
         $start_time = date('Y-m-d',time());
         $end_time = date('Y-m-d',time());
         
        $where = ' where  o.`status`=7 ';

        $where = $where." and o.order_time >= '".$start_time." 00:00:00'";
        $where = $where." and o.order_time <= '".$end_time." 23:59:59' ";
        
        $shop_sql = "select s.shop_id".
                    " ,s.shop_name".
                    ",s.shop_address".
                    ",s.shop_latit".
                    ",s.shop_longit".
                    ",s.shop_scope".
                    " ,s.shop_area".
                    "   ,IF(order_src.order_counts IS NULL, 0, order_src.order_counts) as order_counts ".
                    "  ,IF(order_src.order_amount IS NULL, 0.00, order_src.order_amount) as order_amount".
                    "  ,IF(order_src.real_amount IS NULL, 0.00, order_src.real_amount) as real_amount".
                    "  from db_user_shop s ".
                    "  left join db_app_users a on s.shop_id = a.is_shop".
                    "   left join ".
                    "   ( select user_id,count(order_id) as order_counts,sum(order_amount) as order_amount ,sum(o.real_amount) as real_amount , DATE_FORMAT(o.order_time,'%Y-%m') as order_time from db_order o ".
                            $where.
                    "       GROUP BY user_id".
                    "     )as order_src on order_src.user_id = a.user_id ".
                    "     order by s.sort";

        $data = M()->query($shop_sql);
        //********************************
        if($data){
            return RET(1, "获取数据成功！", $data);
        }else{
           return RET_NO_V(0, "暂无数据！");
        }
    }
/**
     * @api {get} getPnNearby/token/:token/uid/:uid/lon/:lon/lat/:/lat 获取附近跑客
     * @apiGroup pt
     *
     * @apiParam {float} lat 客户地址纬度.
     * @apiParam {float} lon 客户地址經度.
     * @apiParam {Int} uid 跑客唯一ID.
     * @apiParam {String} token 跑客token,每次登录都会更改.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *"retCode": 1,
     *"retDesc": "成功！",
     *"retValue": {
     *"company_id": 大河,           //跑客所屬團隊名稱
     * "id":2           //跑客id
     *"lat": 34.8152060000, //跑客地址纬度
     *"lon": 113.6397350000, //跑客地址经度
     *"dispatch_name": 李某,      //跑客姓名
     *"time": 2017-01-13 14:02:18  //跑客位置更新时间 
     *}*  
     */

    function getPnNearby()
    {
       //鉴权
        managerificationToken();
        $squares = returnSquarePoint(I('lon'), I('lat'));
        $now = strtotime(date('Y-m-d'));
        $company = M("company");
        $Model = M();
        $rets = $company->select();
        $ret_data = array();
        foreach ($rets as $key => $value) {
            //if($key>=1){
            $retd = "select dispatch_id as id,latitude as lat,longitude  as lon ,place_up_time as time,dispatch_name,mobile from db_dispatch where work_status =1 and is_sign = 2 and company_id=" . $value['company_id'] . " and latitude != 0 and latitude>{$squares['right-bottom']['lat']} and latitude<{$squares['left-top']['lat']} and longitude>{$squares['left-top']['lng']} and longitude<{$squares['right-bottom']['lng']} ";
            $ret_data['data'][$key]['company_id'] = $value['company_id'];
            $ret_data['data'][$key]['data'] = $Model->query($retd);
        }
      //dump($ret_data);
        if($ret_data){
                foreach($ret_data['data'] as $k =>$v){
                    if(!empty($v["data"])){
                       
                        foreach($v["data"] as $k2  => $v2)
                        {    
                            $time = strtotime($v2['time']);
                            if($time >= $now)
                            {
                                $v2['company_id'] = $v["company_id"];
                               // unset($v2['time']);
                                $data[] = $v2;
                             }
                        }
                    }
                }
        }else{
            return RET_NO_V(0, "暂无数据！");
        }
         if($data)
        {
             return RET(1, "获取附近跑客成功！", $data);  
        }else{
            return RET_NO_V(0, "暂无数据！"); 
        }
//        RET(1, "获取附近跑客成功！", $ret_data);
    }
/**
     * @api {get} getMobile/token/:token/uid/:uid/dis_id/:dis_id 获取跑客手机号
     * @apiGroup pt
     *
     * @apiParam {float} lat 客户地址纬度.
     * @apiParam {Int} dis_id 跑客唯一ID.
     * @apiParam {Int} uid 用户唯一ID.
     * @apiParam {String} token 用户token,每次登录都会更改.
     *
     * @apiSuccessExample 成功返回:
     *     HTTP/1.1 200 OK
     *     {
     *"retCode": 1,
     *"retDesc": "成功！",
     *"retValue": {
     *"mobile": 13937190779,      //跑客手机号
     *}*  
     */
    function  getPKMobile(){
        //鉴权
        managerificationToken();
        $dis_id = I('dis_id');
        $model = M('dispatch');
        $mobile['mobile'] = $model->where(array('dispatch_id'=>$dis_id))->getField('mobile');
        //echo $model->getLastSql();
       if($mobile){
           return RET(1, "获取数据成功！", $mobile);
       }else{
         return RET_NO_V(0, "暂无数据！"); 
       }
    }
    
   /**
     * @api {get} convertOrder/uid/:uid/token/:token/ 获取某个大客户可以转的订单
     * @apiGroup pt
     * @apiName 获取某个大客户可以转的订单
     *
     * @apiParam {Int} uid 用户ID.
     * @apiParam {String} token 鉴权码.
     * @apiParam {String} shop_id 大客户的shop_id.
     **/
    function heavyBuyerConvertOrderList()
    {
       managerificationToken();
        $shop_id = I('shop_id');
        $app_users = M('app_users');
        $order = M('order');
        $user_id = $app_users->where(array('is_shop'=>$shop_id))->getField('user_id',true);
//        echo $app_users->getLastSql();
//        dump($user_id);
        static $order_id;
        foreach ($user_id as $key =>$value){
        $order_id= implode($order->where(array('user_id'=>$value))->getField(order_id,true),',');
        }
        if($order_id){
        $sql = "select * from db_order_resmsm where order_id in ($order_id) and pay_status =1 and status =2";
        $order_resmsm_data = M()->query($sql);
        $ret_data = array();
        for ($i = 0; $i < count($order_resmsm_data); $i++) {
            $ret_data[] = json_decode($order_resmsm_data[$i]['order_data'], true);
            $ret_data[$i]['dispatch_name'] = get_dispatch_name($order_resmsm_data[$i]['dispatch_id']);
            $ret_data[$i]['mobile'] = get_dispatch_tel($order_resmsm_data[$i]['dispatch_id']);
            $ret_data[$i]['order_time'] = $order_resmsm_data[$i]['order_time'];
        }
        unset($order_id);
        if ($ret_data) {
            return RET(1, "获取订单数据成功！", $ret_data);
        } else {
            return RET_NO_V(0, "暂无数据！");
        }
     }else{
         return RET_NO_V(0, "暂无数据！");
      }
    }
}